package com.study.sbsummary.utils;

import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class DateUtil {
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final SimpleDateFormat DEFAULT_SDF = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
    private static final Map<String, SimpleDateFormat> SDFS = new HashMap<>();
    static {
        SDFS.put(DEFAULT_DATE_FORMAT, DEFAULT_SDF);
    }

    private static SimpleDateFormat getSdfByFormat(String format) {
        SimpleDateFormat sdf = SDFS.get(format);
        if (sdf != null) {
            return sdf;
        }
        synchronized (format) {
            sdf = SDFS.get(format);
            if (sdf == null) {
                sdf = new SimpleDateFormat(format);
                SDFS.put(format, sdf);
            }
        }
        return sdf;
    }

    public static String dateString(Date date) {
        return DEFAULT_SDF.format(date);
    }

    public static long localDateTimeToTimestamp(LocalDateTime localDateTime){
        Long timeStampInSecond = localDateTime.toInstant(ZoneOffset.of("+0")).getEpochSecond();
        return timeStampInSecond;
    }

    public static String timeInSecToDate(long time) {
        return DEFAULT_SDF.format(new Date(time * 1000));
    }

    public static long dateToTimeInMillis(String dateStr) {
        return dateToTimeInMillis(dateStr, DEFAULT_SDF);
    }

    public static long dateToTimeInSec(String dateStr) {
        return dateToTimeInMillis(dateStr, DEFAULT_SDF) / 1000;
    }

    public static long dateToTimeInMillis(String dateStr, String format) {
        return dateToTimeInMillis(dateStr, getSdfByFormat(format));
    }

    public static long dateToTimeInMillis(String dateStr, SimpleDateFormat sdf) {
        try {
            Date date = sdf.parse(dateStr);
            return date.getTime();
        } catch (Exception e) {
            log.warn("failed to parse date {} with format {}", dateStr, sdf.toString());
        }
        return -1;
    }
}
